package b.gate.utils

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}

import scala.util.Try

/**
  * 贲国称 创建于 16/2/24。
  */
object Helper {
  def mapGet[K, V](m: Map[K, V], key: K, error: String): V = {
    val e = m.get(key)
    assert(e.isDefined, error)
    e.get
  }
  private[this] def day2seconds(dt: String): Long = {
    val sdf = new SimpleDateFormat("yyyyMMdd")
    sdf.setLenient(false)
    val cal = Calendar.getInstance()
    cal.setTime(sdf.parse(dt))
    cal.getTime.getTime
  }
  private[this] def seconds2day(time: Long): String = {
    val sdf = new SimpleDateFormat("yyyyMMdd")
    sdf.setLenient(false)
    val cal = Calendar.getInstance()
    cal.setTimeInMillis(time)
    sdf.format(cal.getTime)
  }
  private[this] def dayValidate(dt: String): Boolean = {
    val sdf = new SimpleDateFormat("yyyyMMdd")
    sdf.setLenient(false)
    Try(sdf.parse(dt)).isSuccess
  }
  val SECONDS1DAY: Long = 86400000L
  def days(from: String, to: String): Int = {
    ((day2seconds(to) - day2seconds(from)) / SECONDS1DAY).toInt
  }
  def dueDay(from: String, term: String): String = {
    assert(term.length > 1, "不支持的存期格式[过短]")
    val unit = term.takeRight(1)
    assert(Set("D", "M", "Y").contains(unit), "不支持的存期格式[单位非D/M/Y]")
    val num = term.dropRight(1).toInt
    unit match {
      case "D" => seconds2day(day2seconds(from) + num * SECONDS1DAY)
      case "M" =>
        val m1 = from.substring(4, 6).toInt + num
        val m = if (m1 > 12) m1 % 12 else if (m1 <= 0) m1 % 12 + 12 else m1
        val y1 = from.take(4).toInt
        val y = if (m1 > 12) y1 + m1 / 12 else if (m1 <= 0) y1 + m1 / 12 - 1 else y1
        assert(y > 0 &&  y < 10000, "不支持的存期格式[数值越界]")
        var to = "%04d".format(y) + "%02d".format(m) + from.takeRight(2)
        var d = from.takeRight(2).toInt
        if (d > 28) {
          while (!dayValidate(to)) {
            d -= 1
            to = "%04d".format(y) + "%02d".format(m) + "%02d".format(d)
          }
        }
        to
      case "Y" =>
        val y = from.take(4).toInt + num
        assert(y > 0 &&  y < 10000, "不支持的存期格式[数值越界]")
        var to = "%04d".format(y) + from.takeRight(4)
        if (from.substring(4, 6) == "02") {
          var d = from.takeRight(2).toInt
          while (!dayValidate(to)) {
            d -= 1
            to = "%04d".format(y) + from.substring(4, 6) + "%02d".format(d)
          }
        }
        to
    }
  }
  def timestamp(): String = {
    val df: SimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS")
    df.format(new Date())
  }
  def today: String = timestamp().take(8)
  def format(c: Calendar, f: String = "yyyyMMdd"): String = {
    val df: SimpleDateFormat = new SimpleDateFormat(f)
    df.format(c.getTime)
  }
}
